/*

This software is licensed under the terms of the MIT licence.

Copyright (c) 2009 Mihaly Heder

Permission is hereby granted, free of charge, to any person obtaining a copy of 
this software and associated documentation files (the "Software"), to deal in the 
Software without restriction, including without limitation the rights to use, copy, 
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
and to permit persons to whom the Software is furnished to do so, subject to the 
following conditions:

The above copyright notice and this permission notice shall be included in all copies 
or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
SOFTWARE.

*/
/*
 * XMLHelper.java
 *
 * Created on March 19, 2007, 11:43 PM
 *
 *
 */

package info.mihaly.heder.xmlutils;

import java.io.File;
import java.io.IOException;

import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.NodeList;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import java.util.Iterator;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;



/**
 * 
 * @author merlin
 */
public class XMLHelper {

	static class MyNamespaceContext implements NamespaceContext {

		private Map<String,String> map;

		public MyNamespaceContext() {
			map = new HashMap<String,String>();
		}

		public void setNamespace(String prefix, String namespaceURI) {
			map.put(prefix, namespaceURI);
		}

		public String getNamespaceURI(String prefix) {
			return (String) map.get(prefix);
		}

		public String getPrefix(String namespaceURI) {
			Set<String> keys = map.keySet();
			for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();)
			{
				String prefix = (String) iterator.next();
				String uri = (String) map.get(prefix);
				if (uri.equals(namespaceURI))
					return prefix;
			}
			return null;
		}

		public Iterator<String> getPrefixes(String namespaceURI) {
			List<String> prefixes = new ArrayList<String>();
			Set<String> keys = map.keySet();
			for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();)
			{
				String prefix = (String) iterator.next();
				String uri = (String) map.get(prefix);
				if (uri.equals(namespaceURI))
					prefixes.add(prefix);
			}
			return prefixes.iterator();
		}
	}

	static XPathFactory xPathFactory;

	/**
	 * This function evaluates an XPath expression on a given document tree, and
	 * returns a NodeList.
	 * 
	 * @param doc
	 *            a w3c document to work on
	 * @param xpathStr
	 *            the XPath expression
	 * @return a w3c NodeSet
	 */
	public static NodeList getNodeListByXPath(Document doc, String xpathStr)
			throws XPathExpressionException {

		if (xPathFactory == null) {
			xPathFactory = XPathFactory.newInstance();
		}

		XPath xpath = xPathFactory.newXPath();
		XPathExpression expr = xpath.compile(xpathStr);
		Object result = expr.evaluate(doc, XPathConstants.NODESET);
		NodeList nodes = (NodeList) result;
		return nodes;
	}

	public static NodeList getNodeListByXPathNs(Document doc, String prefix,
			String nsuri, String xpathStr) throws XPathExpressionException {

		if (xPathFactory == null) {
			xPathFactory = XPathFactory.newInstance();
		}

		XPath xpath = xPathFactory.newXPath();
		MyNamespaceContext nsc = new MyNamespaceContext();
		nsc.setNamespace(prefix, nsuri);
		xpath.setNamespaceContext(nsc);
		XPathExpression expr = xpath.compile(xpathStr);
		Object result = expr.evaluate(doc, XPathConstants.NODESET);
		NodeList nodes = (NodeList) result;
		return nodes;
	}

	/**
	 * This function evaluates an XPath expression on a given document tree, and
	 * returns a NodeList.
	 * 
	 * @param doc
	 *            a w3c document to work on
	 * @param xpathStr
	 *            the XPath expression
	 * @return a w3c NodeSet
	 */
	public static String getStringByXPath(Document doc, String xpathStr)
			throws XPathExpressionException {

		if (xPathFactory == null) {
			xPathFactory = XPathFactory.newInstance();
		}

		XPath xpath = xPathFactory.newXPath();
		XPathExpression expr = xpath.compile(xpathStr);
		String result = expr.evaluate(doc);
		return result;
	}

	/**
	 * This funtction parses a given xml file and returns the w3c Document
	 * object corresponding to the content of the file.
	 * 
	 * @param file
	 *            the file to parse
	 * @return a w3c document
	 */
	public static Document getDocumentFromXmlFile(File file)
			throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setValidating(false);
		return (factory.newDocumentBuilder().parse(file));
	}
}
